/*
 * CS_LAST_WEEK_RANK_LIST.cpp
 *
 *  Created on: 2013. 6. 10.
 *      Author: the2
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../Proxy.h"
#include "../../../../protocol/iFriends.h"
#include "../../NLogic/Static.h"

namespace ProjectZ { namespace NCommand {
/*
// 전 주 랭킹 리스트 읽어오기 (주간 랭킹)
ZNO_CS_LAST_WEEK_RANK_LIST	0x2804
{
	u16 u16count;
	{
		u32 u32gid;
	}
}

ZNO_SC_LAST_WEEK_RANK_LIST	0x2805
{
	s16 s16ack;
	u16 u16count;
	count{									/// MAX : 12
		u32 	u32gid;							// gid
		u32	u32point;						// 점수
	}
}
*/
void Command::CS_LAST_WEEK_RANK_LIST(User * pUser, ::Network::Packet * pPacket)
{
	PREPARE_PACKET;

	struct Score
	{
		uint32_t	curweek;
		uint32_t	lastweek;
		time_t		reg_date;

		Score() : curweek(0), lastweek(0), reg_date(0) {}
	};

	uint16_t count = 0;

	*pPacket >> count;

	if(100 < count)
	{
		::Network::Packet * ack = ::Network::GETPACKETPOOL()->SEND_NEW();

		*ack << static_cast<int16_t>(ACK_UNKNOWN_ERROR)
				<< static_cast<uint16_t>(0);

		ack->MakePacket(CMD_SC_LAST_WEEK_RANK_LIST);
		pUser->Send(ack);
	}

	time_t initTime = NLogic::NFunction::GetWeekInitTime();

	::Network::Packet * ack = ::Network::GETPACKETPOOL()->SEND_NEW();
	*ack << static_cast<int16_t>(ACK_OK)
			<< count;

	for( int i = 0 ; i < count ; i++ )
	{
		uint32_t target_userseq =  0;
		*pPacket >> target_userseq;

		std::string scoreKey = "score_" + std::to_string(target_userseq);

		size_t valuelen = 0;
		uint32_t flags = 0;
		memcached_return_t rc;
		NLogic::MemResultSet resultSet;
		::ProjectZ::NLogic::Memcached * clsMemcached = ::ProjectZ::NLogic::Static::Instance().GETMEMCACHED();
		resultSet.m_pVal = clsMemcached->Get(scoreKey.c_str(), &valuelen, &flags, &rc);

		Score score;
		if( rc != MEMCACHED_SUCCESS )
		{

		}
		else
		{
			resultSet.Init( resultSet.m_pVal, valuelen );

			while ( resultSet.MoreRecord() )
			{
				score.curweek = atoi(resultSet.ROW[0]);
				score.lastweek = atoi(resultSet.ROW[1]);
				score.reg_date = atoi(resultSet.ROW[2]);
			}
		}

		*ack << target_userseq;
		if (score.reg_date <= initTime)
			*ack << static_cast<uint32_t>(0);
		else
			*ack << score.curweek;
	}

	ack->MakePacket(CMD_SC_LAST_WEEK_RANK_LIST);
	pUser->Send(ack);
}

} /*NCommand*/ } /*ProjectZ*/


